package mof.gov.dmdc.view.backing.staticexport;

import java.io.BufferedInputStream;
import java.io.IOException;

import java.io.InputStream;
import java.io.PrintWriter;

import java.sql.SQLException;

import java.util.ArrayList;
import java.util.List;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;

import javax.faces.model.SelectItem;

import javax.servlet.http.HttpServletResponse;

import mof.gov.dmdc.model.applicationmodule.extra.COAModuleImpl;
import mof.gov.dmdc.view.common.Common;

import oracle.jbo.AttributeDef;
import oracle.jbo.Row;
import oracle.jbo.ViewCriteria;
import oracle.jbo.ViewCriteriaRow;
import oracle.jbo.ViewObject;

public class StaticExportBean {

    private String groupID = "1";
    private List listDM;
    private String tableName;
    String fileName;
    String tcvnFileName;

    public StaticExportBean() {
        super();
        listDM = createListTable(groupID);
        tableName = ((SelectItem)listDM.get(0)).getValue().toString();
    }

    public void setGroupID(String groupID) {
        this.groupID = groupID;
    }

    public String getGroupID() {
        return groupID;
    }

    public void setListDM(List listDM) {
        this.listDM = listDM;
    }

    public List getListDM() {
        return listDM;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getTableName() {
        return tableName;
    }

    public void filterAction(ActionEvent actionEvent) {
        ViewObject vo = Common.getViewObjectForIterator("LogTransTextViewIterator");
        ViewCriteria criteria = null;
        try {
            criteria = vo.getViewCriteria();
            criteria.clear();
        } catch (Exception e) {
            criteria = null;
        }
        criteria = vo.createViewCriteria();
        ViewCriteriaRow row = criteria.createViewCriteriaRow();
        row.setAttribute(1, tableName);
        row.setOperator(1, "=");
        criteria.addRow(row);
        vo.applyViewCriteria(criteria);
        vo.executeQuery();
        vo.clearCache();
    }

    public void groupChange(ValueChangeEvent valueChangeEvent) {
        groupID = valueChangeEvent.getNewValue().toString();
        listDM.clear();
        listDM = createListTable(groupID);
        tableName = ((SelectItem)listDM.get(0)).getValue().toString();
    }

    private List createListTable(String groupId) {
        ArrayList array = new ArrayList();
        switch (Integer.parseInt(groupId)) {
        case 1: //
            array.add(new SelectItem("DM_CHUONG", "Danh m\u1EE5c ch\u01B0\u01A1ng"));
            array.add(new SelectItem("DM_NGANHKT", "Danh m\u1EE5c ng\u00E0nh kinh t\u1EBF"));
            array.add(new SelectItem("DM_NDKT", "Danh m\u1EE5c n\u1ED9i dung kinh t\u1EBF"));
            array.add(new SelectItem("DM_CTMT", "Danh m\u1EE5c ch\u01B0\u01A1ng tr\u00ECnh m\u1EE5c ti\u00EAu"));
            array.add(new SelectItem("DM_NGUONCHI", "Danh m\u1EE5c ngu\u1ED3n chi ng\u00E2n s\u00E1ch"));
            array.add(new SelectItem("DM_CAPNS", "Danh m\u1EE5c c\u1EA5p ng\u00E2n s\u00E1ch"));
            array.add(new SelectItem("DM_NVCHI", "Danh m\u1EE5c nhi\u1EC7m v\u1EE5 chi"));
            break;
        case 2:
            array.add(new SelectItem("DM_DVQHNS", "Danh m\u1EE5c \u0111\u01A1n v\u1ECB c\u00F3 quan h\u1EC7 ng\u00E2n s\u00E1ch"));
            array.add(new SelectItem("DM_DVQHNS_MANS", "Danh m\u1EE5c m\u00E3 ng\u00E2n s\u00E1ch"));
            array.add(new SelectItem("DM_DVQHNS_MATCNS", "Danh m\u1EE5c m\u00E3 t\u1ED5 ch\u1EE9c ng\u00E2n s\u00E1ch"));
            array.add(new SelectItem("DM_DVQHNS_DV", "Danh m\u1EE5c m\u00E3 QHNS"));
            array.add(new SelectItem("DB_DTNT", "Danh m\u1EE5c \u0111\u1ED1i t\u01B0\u1EE3ng n\u1ED9p thu\u1EBF"));
            array.add(new SelectItem("DM_MST_CANHAN", "Danh m\u1EE5c m\u00E3 s\u1ED1 thu\u1EBF c\u00E1 nh\u00E2n"));
            array.add(new SelectItem("DB_BAOCAO", "Danh m\u1EE5c b\u00E1o c\u00E1o"));
            array.add(new SelectItem("DB_CHITIEU", "Danh m\u1EE5c ch\u1EC9 ti\u00EAu"));
            array.add(new SelectItem("DM_TKKT", "Danh m\u1EE5c m\u00E3 qu\u1EF9"));
            array.add(new SelectItem("DM_DVQHNS_XDCB", "Danh m\u1EE5c m\u00E3 d\u1EF1 \u00E1n XDCB"));
            array.add(new SelectItem("DM_LOAIVON", "Danh m\u1EE5c m\u00E3 lo\u1EA1i v\u1ED1n"));
            array.add(new SelectItem("DM_NGUONCHI_DTSN",
                                     "Danh m\u1EE5c m\u00E3 ngu\u1ED3n chi \u0111\u1EA7u t\u01B0, ch\u01B0\u01A1ng tr\u00ECnh m\u1EE5c ti\u00EAu s\u1EF1 nghi\u1EC7p"));
            array.add(new SelectItem("DM_NHOMDA_DT", "Danh m\u1EE5c m\u00E3 nh\u00F3m d\u1EF1 \u00E1n \u0111\u1EA7u t\u01B0"));
            break;
        case 3:
            array.add(new SelectItem("DM_QUY", "Danh m\u1EE5c M\u00E3 qu\u1EF9"));
            array.add(new SelectItem("DM_TKKT_CTNB", "Danh m\u1EE5c t\u00E0i kho\u1EA3n t\u1EF1 nhi\u00EAn"));
            array.add(new SelectItem("DM_NDKT", "Danh m\u1EE5c n\u1ED9i dung kinh t\u1EBF"));
            array.add(new SelectItem("DM_CAPNS", "Danh m\u1EE5c c\u1EA5p ng\u00E2n s\u00E1ch"));
            array.add(new SelectItem("DM_DBHC", "Danh m\u1EE5c \u0111\u1ECBa b\u00E0n h\u00E0nh ch\u00EDnh"));
            array.add(new SelectItem("DM_CHUONG", "Danh m\u1EE5c m\u00E3 ch\u01B0\u01A1ng"));
            array.add(new SelectItem("DM_NGANHKT", "Danh m\u1EE5c ng\u00E0nh kinh t\u1EBF"));
            array.add(new SelectItem("DM_CTMT", "Danh m\u1EE5c ch\u01B0\u01A1ng tr\u00ECnh m\u1EE5c ti\u00EAu, d\u1EF1 \u00E1n"));
            array.add(new SelectItem("DM_KBNN", "Danh m\u1EE5c kho b\u1EA1c nh\u00E0 n\u01B0\u1EDBc"));
            array.add(new SelectItem("DM_NGUONCHI", "Danh m\u1EE5c ngu\u1ED3n chi NSNN"));
            array.add(new SelectItem("DM_DUPHONG", "Danh m\u1EE5c d\u1EF1 ph\u00F2ng"));
            break;
        case 4:
            array.add(new SelectItem("DB_HHXNK", "Danh m\u1EE5c h\u00E0ng h\u00F3a xu\u1EA5t nh\u1EADp kh\u1EA9u"));
            break;
        case 5:
            array.add(new SelectItem("DM_DN_THAMDINHGIA", "Danh m\u1EE5c doanh nghi\u1EC7p th\u1EA9m \u0111\u1ECBnh gi\u00E1"));
            array.add(new SelectItem("DM_THAMDINHVIEN", "Danh m\u1EE5c th\u1EA9m \u0111\u1ECBnh vi\u00EAn v\u1EC1 gi\u00E1"));
            array.add(new SelectItem("DM_CTYKIEMTOAN", "Danh m\u1EE5c doanh nghi\u1EC7p ki\u1EC3m to\u00E1n \u0111\u1ED9c l\u1EADp"));
            array.add(new SelectItem("DM_KIEMTOANVIEN", "Danh m\u1EE5c ki\u1EC3m to\u00E1n vi\u00EAn"));
            array.add(new SelectItem("DM_CTYKETOAN", "Danh m\u1EE5c doanh nghi\u1EC7p k\u1EBF to\u00E1n"));
            array.add(new SelectItem("DM_KETOANVIEN", "Danh m\u1EE5c k\u1EBF to\u00E1n vi\u00EAn"));
            break;
        case 6:
            array.add(new SelectItem("DM_DOITUONG_HCS", "Danh m\u1EE5c \u0111\u1ED1i t\u01B0\u1EE3ng h\u01B0\u1EDFng ch\u00EDnh s\u00E1ch"));
            array.add(new SelectItem("DM_LUONG_TTHIEU", "Danh m\u1EE5c m\u1EE9c l\u01B0\u01A1ng t\u1ED1i thi\u1EC3u"));
            array.add(new SelectItem("DM_PHUCAP", "Danh m\u1EE5c ph\u1EE5 c\u1EA5p"));
            array.add(new SelectItem("DM_NGACHCC", "Danh m\u1EE5c ng\u1EA1ch c\u00F4ng ch\u1EE9c"));
            array.add(new SelectItem("DM_BACLUONG_CHITIET",
                                     "Danh m\u1EE5c b\u1EADc l\u01B0\u01A1ng v\u00E0 h\u1EC7 s\u1ED1 l\u01B0\u01A1ng chi ti\u1EBFt theo ng\u1EA1ch c\u00F4ng ch\u1EE9c"));
            array.add(new SelectItem("DM_HESO_DONG_BHIEM_BL", "Danh m\u1EE5c h\u1EC7 s\u1ED1 \u0111\u00F3ng b\u1EA3o hi\u1EC3m theo b\u1EADc l\u01B0\u01A1ng"));
            array.add(new SelectItem("DM_LOAI_BHIEM_NGACH", "Danh m\u1EE5c h\u1EC7 s\u1ED1 \u0111\u00F3ng b\u1EA3o hi\u1EC3m theo ng\u1EA1ch l\u01B0\u01A1ng"));
            array.add(new SelectItem("DM_LOAI_BHIEM", "Danh m\u1EE5c lo\u1EA1i b\u1EA3o hi\u1EC3m"));
            array.add(new SelectItem("DM_LOAI_HDONG", "Danh m\u1EE5c lo\u1EA1i h\u1EE3p \u0111\u1ED3ng"));
            array.add(new SelectItem("DM_TRINHDO_CBCC", "Danh m\u1EE5c tr\u00ECnh \u0111\u1ED9 c\u00E1n b\u1ED9 c\u00F4ng ch\u1EE9c"));
            break;
        case 7:
            array.add(new SelectItem("DB_CQTCHINH", "Danh m\u1EE5c c\u01A1 quan t\u00E0i ch\u00EDnh"));
            array.add(new SelectItem("DB_CQTHUE", "Danh m\u1EE5c c\u01A1 quan thu\u1EBF"));
            array.add(new SelectItem("DB_CQKBAC", "Danh m\u1EE5c c\u01A1 quan kho b\u1EA1c"));
            array.add(new SelectItem("DB_CQHQUAN", "Danh m\u1EE5c c\u01A1 quan h\u1EA3i quan"));
            array.add(new SelectItem("DB_CQCKHOAN", "Danh m\u1EE5c c\u01A1 quan ch\u1EE9ng kho\u00E1n"));
            array.add(new SelectItem("DB_CQDTRU", "Danh m\u1EE5c c\u01A1 quan d\u1EF1 tr\u1EEF"));
            array.add(new SelectItem("DM_CQTHU", "Danh m\u1EE5c c\u01A1 quan thu"));
            array.add(new SelectItem("DB_DTHU", "Danh m\u1EE5c \u0111i\u1EC3m thu"));
            break;
        case 8:
            array.add(new SelectItem("DM_BONGANH", "Danh m\u1EE5c b\u1ED9, ban, ng\u00E0nh"));
            array.add(new SelectItem("DM_NGANHANG", "Danh m\u1EE5c m\u00E3 ng\u00E2n h\u00E0ng"));
            array.add(new SelectItem("DM_TAPDOAN_KT", "Danh m\u1EE5c t\u1EADp \u0111o\u00E0n kinh t\u1EBF"));
            array.add(new SelectItem("DM_TCTY_NN", "Danh m\u1EE5c t\u1ED5ng c\u00F4ng ty nh\u00E0 n\u01B0\u1EDBc"));
            array.add(new SelectItem("DM_CTY_NN", "Danh m\u1EE5c c\u00F4ng ty nh\u00E0 n\u01B0\u1EDBc"));
            array.add(new SelectItem("DM_CTY_CP_LD_TNHH",
                                     "Danh m\u1EE5c c\u00F4ng ty c\u1ED5 ph\u1EA7n, c\u00F4ng ty li\u00EAn doanh, c\u00F4ng ty TNHH, c\u00F4ng ty 100% v\u1ED1n n\u01B0\u1EDBc ngo\u00E0i"));
            break;
        case 9:
            array.add(new SelectItem("DM_VUNGKT", "Danh m\u1EE5c m\u00E3 v\u00F9ng kinh t\u1EBF"));
            array.add(new SelectItem("DB_QGIA", "Danh m\u1EE5c qu\u1ED1c gia"));
            array.add(new SelectItem("DB_TIENTE", "Danh m\u1EE5c ti\u1EC1n t\u1EC7"));
            array.add(new SelectItem("DM_TIGIA", "Danh m\u1EE5c t\u1EF7 gi\u00E1 theo quy \u0111\u1ECBnh c\u1EE7a b\u1ED9 t\u00E0i ch\u00EDnh"));
            array.add(new SelectItem("DM_NGANHKTQD", "Danh m\u1EE5c ng\u00E0nh kinh t\u1EBF qu\u1ED1c d\u00E2n"));
            break;
        }
        return array;
    }

    public String downloadFile() throws IOException {
        ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse)ectx.getResponse();

        oracle.sql.BFILE bfile = null;
        COAModuleImpl am = (COAModuleImpl)Common.getAppModuleForDataControl("COAModuleDataControl");

        String actualFileName = getFilenameFull(fileName);

        if (actualFileName == null)
            return null;
        bfile = am.getBFILELocator("DMDC_EXP", actualFileName);

        if (bfile == null) {
            return null;
        }
        try {
            bfile.openFile();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Khong open duoc bfile!!!!!");
        }


        // Open the Input Binary Stream with  getBinaryStream method of
        // oracle.sql.BFILE class
        InputStream instream = null;
        try {
            instream = new BufferedInputStream(bfile.getBinaryStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            response.setContentType("text/plain;charset=UTF-8");

            //TCVN3: response.setContentType("text/plain;charset=windows-1252");

            response.setHeader("Content-disposition", "attachment; filename=" + actualFileName);

            PrintWriter out = response.getWriter();
            int chunk = 32767;
            long length = 0;
            StringBuffer sb = null;

            try {
                length = bfile.length();
                sb = new StringBuffer((int)(length / chunk) + 2);
                System.out.println("Total length (bytes):" + length);
                //response.setContentLength((int)length);
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            // Create temporary buffer for read
            byte[] buffer = new byte[chunk];

            // Fetch data
            int i = 0;
            length = instream.read(buffer);
            while ((length) != -1) {
                i++;
                try {
                    sb.append(new String(buffer, "UTF-8"));
                    // This is to ensure data read will be NEW and precisely populated
                    buffer = new byte[chunk];

                    if (i % 10 == 0) {
                        out.println(sb.toString());
                        sb = new StringBuffer();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(i);
                System.out.println("Read DONE: " + (i * chunk));
                length = instream.read(buffer);
            }
            System.out.println("Read DONE!" + (i * chunk));

            // Close input stream
            instream.close();

            // close file handler
            try {
                bfile.closeFile();
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            try {
                out.println(sb.toString());
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }

            //please dont forget to flush the response
            response.flushBuffer();

            out.close();
            FacesContext.getCurrentInstance().responseComplete();
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
            //do nothing
        } finally {
            if (bfile != null) {
                try {
                    // 7. Close the statement
                    instream.close();
                    bfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String downloadTcvn3File() {

        ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse)ectx.getResponse();

        oracle.sql.BFILE bfile = null;
        COAModuleImpl am = (COAModuleImpl)Common.getAppModuleForDataControl("COAModuleDataControl");


        String actualFileName = getFilenameFull(tcvnFileName);
        if (actualFileName == null)
            return null;
        bfile = am.getBFILELocator("DMDC_EXP", actualFileName);
        if (bfile == null) {
            return null;
        }
        try {
            bfile.openFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        InputStream instream = null;
        try {
            instream = new BufferedInputStream(bfile.getBinaryStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            response.setContentType("text/plain;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + actualFileName);
            PrintWriter out = response.getWriter();
            int chunk = 32767;
            long length = 0;
            StringBuffer sb = null;
            try {
                length = bfile.length();
                sb = new StringBuffer((int)(length / chunk) + 2);
                System.out.println("Total length (bytes):" + length);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            byte[] buffer = new byte[chunk];
            int i = 0;
            length = instream.read(buffer);
            while ((length) != -1) {
                i++;
                try {
                    sb.append(new String(buffer, "UTF-8"));
                    buffer = new byte[chunk];
                    if (i % 10 == 0) {
                        out.println(sb.toString());
                        sb = new StringBuffer();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(i);
                System.out.println("Read DONE: " + (i * chunk));
                length = instream.read(buffer);
            }
            System.out.println("Read DONE!" + (i * chunk));
            instream.close();
            try {
                bfile.closeFile();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            try {
                out.println(sb.toString());
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.flushBuffer();
            out.close();
            FacesContext.getCurrentInstance().responseComplete();
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            if (bfile != null) {
                try {
                    instream.close();
                    bfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getFilename(String fullPath) {
        int dot = fullPath.lastIndexOf(".");
        int sep = fullPath.lastIndexOf("/");
        return fullPath.substring(sep + 1, dot);
    }

    public String getFilenameFull(String fullPath) {
        if (fullPath == null)
            return null;
        int sep = fullPath.lastIndexOf("/");
        return fullPath.substring(sep + 1);
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() {
        return fileName;
    }

    public void setTcvnFileName(String tcvnFileName) {
        this.tcvnFileName = tcvnFileName;
    }

    public String getTcvnFileName() {
        return tcvnFileName;
    }
}
